package com.efounder.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.efounder.activity.CollectionActivity;
import com.efounder.activity.MallAddressListActivity;
import com.efounder.activity.MallGeneralOrderActivity;
import com.efounder.adapter.OrderAdapter;
import com.efounder.bean.OrderList;
import com.efounder.bean.UpdateOrderBadgeEvent;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.widget.BadgeView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.utils.Constants;
import com.efounder.http.EFHttpRequest;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.mobilemall.R;
import com.efounder.utils.MallRequestUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import static com.efounder.utils.MallRequestUtil.GOOD_COLLECT_NUM;
import static com.efounder.utils.MallRequestUtil.ORDER_LIST_URL;

/**
 * @author 隗德彪
 * 商城，我的界面
 */
public class MyPagerFragment extends BaseFragment implements View.OnClickListener{

    private String TAG = this.getClass().getSimpleName();
    private View rootView;
    private RelativeLayout my_order;
    private RelativeLayout collect;
    private RelativeLayout follow;
    private RelativeLayout footprint;
    private RelativeLayout review;
    private TextView tv_title;
    private ImageView headView;
    private ImageView iv_back;
    private TextView tvUserName,collect_count;
    /**
     * 是否创建
     */
    protected boolean isCreate = false;

    private BadgeView toCheckBadge, toShipBadge, toReceiveBadge, toCommentBadge, refundBadge;
    private int toShipCount = 0, toCheckCount = 0, toReceiveCount = 0, toCommentCount = 0, refundCount = 0;
    private boolean hideTitle = false;

    public MyPagerFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_my_pager, container, false);
        initParams();
        initView();
        initUserData();
        initBadgeData();
        EventBus.getDefault().register(this);
        return rootView;
    }

    /**
     * 是否隐藏标题栏
     */
    private void initParams() {
        if (getArguments() != null && getArguments().getBoolean("hideTitle", false)) {
            hideTitle = true;
        }
    }

    private void initView() {
        if (hideTitle) {
            rootView.findViewById(R.id.title).setVisibility(View.GONE);
        }
        my_order = rootView.findViewById(R.id.myOrder);
        collect = rootView.findViewById(R.id.collect);
        follow = rootView.findViewById(R.id.follow);
        footprint = rootView.findViewById(R.id.footprint);
        review = rootView.findViewById(R.id.review);
        iv_back = rootView.findViewById(R.id.iv_back);
        collect_count = rootView.findViewById(R.id.collect_count);
        my_order.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        collect.setOnClickListener(this);
        follow.setOnClickListener(this);
        footprint.setOnClickListener(this);
        review.setOnClickListener(this);
        LinearLayout rlToCheck = (LinearLayout) rootView.findViewById(R.id.rl_toCheck);
        ImageView ivToCheck = (ImageView) rootView.findViewById(R.id.unpaid);
        toCheckBadge = new BadgeView(getActivity(), ivToCheck);
        rlToCheck.setOnClickListener(this);
        LinearLayout rlToShip = (LinearLayout) rootView.findViewById(R.id.rl_toShip);
        ImageView ivToShip = (ImageView) rootView.findViewById(R.id.undeliver);
        toShipBadge = new BadgeView(getActivity(), ivToShip);
        rlToShip.setOnClickListener(this);
        LinearLayout rlToReceive = (LinearLayout) rootView.findViewById(R.id.rl_toReceive);
        ImageView ivToReceive = (ImageView) rootView.findViewById(R.id.unreceive);
        toReceiveBadge = new BadgeView(getActivity(), ivToReceive);
        rlToReceive.setOnClickListener(this);
        LinearLayout rlToComment = (LinearLayout) rootView.findViewById(R.id.rl_toComment);
        ImageView ivToComment = (ImageView) rootView.findViewById(R.id.uncomment);
        toCommentBadge = new BadgeView(getActivity(), ivToComment);
        rlToComment.setOnClickListener(this);
        LinearLayout rlToRefund = (LinearLayout) rootView.findViewById(R.id.rl_toRefund);
        ImageView ivRefund = (ImageView) rootView.findViewById(R.id.refund);
        refundBadge = new BadgeView(getActivity(), ivRefund);
        rlToRefund.setOnClickListener(this);
        tv_title = rootView.findViewById(R.id.tv_title);
        headView = rootView.findViewById(R.id.head);
        tvUserName = rootView.findViewById(R.id.tv_user_name);
        tv_title.setText(R.string.mail_my);
        RelativeLayout rlMyAddress = (RelativeLayout) rootView.findViewById(R.id.rl_my_address);
        rlMyAddress.setOnClickListener(this);
    }

    /**
     * 用户数据
     * 名称，头像
     */
    private void initUserData() {
        User user = WeChatDBManager.getInstance().getOneUserById(Integer.valueOf(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID)));
        tvUserName.setText(user.getNickName());
        Glide.with(this)
                .load(user.getAvatar())
                .apply(new RequestOptions().transform(new CircleCrop()))
                .into(headView);
    }

    private void initBadgeData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("status", "all");
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("num", "0");
        map.put("pageSize", "5");
        MallRequestUtil.getRequest(TAG, ORDER_LIST_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    Gson gson = new GsonBuilder().serializeNulls().create();
                    OrderList orderList = gson.fromJson(response, OrderList.class);
                    if (orderList.getResult().equals("success") && orderList.getStatusCounts() != null) {
                        resetCount();
                        for (OrderList.StatusCountsBean statusCountsBean : orderList.getStatusCounts()) {
                            if (statusCountsBean.getPaymentStatus().equals(OrderAdapter.MALL_NEED_PAY)) {
                                toCheckCount = statusCountsBean.getCount();
                            } else if (statusCountsBean.getPaymentStatus().equals(OrderAdapter.MALL_NEED_SEND_GOOD)) {
                                toShipCount = statusCountsBean.getCount();
                            } else if (statusCountsBean.getPaymentStatus().equals(OrderAdapter.MALL_NEED_RECEIVE)) {
                                toReceiveCount = statusCountsBean.getCount();
                            } else if (statusCountsBean.getPaymentStatus().equals(OrderAdapter.MALL_NEED_COMMENT)) {
                                toCommentCount = statusCountsBean.getCount();
                            } else if (statusCountsBean.getPaymentStatus().equals(OrderAdapter.MALL_REFUND)) {
                                refundCount = statusCountsBean.getCount();
                            }
                        }
                    }
                    refreshBadge();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {
            }
        });


    }

    @Override
    public void onResume() {
        super.onResume();
        getMyCollect();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isCreate = true;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isCreate) {
            getMyCollect();
            initBadgeData();
        }
    }

    private void getMyCollect() {
        //获取收藏商品的数量
        HashMap<String, String> hashMap = new HashMap();
        hashMap.put("userId", EnvironmentVariable.getUserName());
        MallRequestUtil.getRequest(TAG, GOOD_COLLECT_NUM, hashMap, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject =new JSONObject(response);
                    String result = jsonObject.getString("result");
                    if("success".equals(result)){
                        int collectCount = jsonObject.getInt("collectCount");
                        collect_count.setText(collectCount+"");
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {

            }
        });
    }


    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.myOrder){
            startActivity(new Intent(getContext(), MallGeneralOrderActivity.class));
        }else if(v.getId() == R.id.collect){
            startActivity(new Intent(getContext(), CollectionActivity.class));
        } else if (v.getId() == R.id.rl_my_address) {
            Intent intent = new Intent(getActivity(), MallAddressListActivity.class);
            startActivity(intent);
        } else if (v.getId() == R.id.rl_toCheck) {
            Intent intent = new Intent(getActivity(), MallGeneralOrderActivity.class);
            intent.putExtra("targetIndex", 1);
            startActivity(intent);
        } else if (v.getId() == R.id.rl_toShip) {
            Intent intent = new Intent(getActivity(), MallGeneralOrderActivity.class);
            intent.putExtra("targetIndex", 2);
            startActivity(intent);
        } else if (v.getId() == R.id.rl_toReceive) {
            Intent intent = new Intent(getActivity(), MallGeneralOrderActivity.class);
            intent.putExtra("targetIndex", 3);
            startActivity(intent);
        } else if (v.getId() == R.id.rl_toComment) {
            Intent intent = new Intent(getActivity(), MallGeneralOrderActivity.class);
            intent.putExtra("targetIndex", 4);
            startActivity(intent);
        }else  if(v.getId()==R.id.iv_back){
            getActivity().onBackPressed();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 1)
    public void onSolveCartBadgeEvent(UpdateOrderBadgeEvent event) {
        initBadgeData();
    }
    private void setUpBadge(BadgeView badge, int count) {
//        badge.setBadgeMargin(50, 0);
        badge.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
        badge.setTextSize(11);
        badge.setTextColor(getResources().getColor(R.color.white));
        badge.setBadgeBackgroundColor(Color.RED);
        if (count > 99) {
            badge.setText("99+");
        } else {
            badge.setText(count + "");
        }
        if (count <= 0 && count != -1) {
            badge.setVisibility(View.INVISIBLE);
        } else {
            badge.show();
        }
    }

    /**
     * 重置角标
     */
    private void resetCount() {
        toShipCount = 0; toCheckCount = 0; toReceiveCount = 0; toCommentCount = 0; refundCount = 0;
    }

    private void refreshBadge() {
        setUpBadge(toCheckBadge,toCheckCount);
        setUpBadge(toShipBadge,toShipCount);
        setUpBadge(toReceiveBadge,toReceiveCount);
        setUpBadge(toCommentBadge,toCommentCount);
        setUpBadge(refundBadge,refundCount);
    }

    @Override
    public void onStop() {
        super.onStop();
        EFHttpRequest.cancelRequest(TAG);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
